<script setup>
import { reactive, ref } from 'vue';
import router from '@/router';
import loginApi from '@/api/login_api.js';
//import { Admin,Logout } from '@element-plus/icons-vue';
// import { adminStore, tokenStore } from '../store/store.js';
const activeIndex = ref('1')

// 取出当前登录用户的信息
const loginAdmin = ref({
  name: "未登录",
  adminname: "",
  username: ""
});
const loginUser = ref({
  role: localStorage.getItem("role") || "admin", // 默认为admin，实际应该从登录信息中获取
  id: localStorage.getItem("userId") || null
});
getLogin();

async function getLogin() {
  let token = localStorage.getItem("token");
  if (!token) {
    // 跳转到登录页
    router.push('/login');
  }

  try {
    // 根据存储的角色信息决定调用哪个接口
    const role = localStorage.getItem("role");
    let res;
    if (role === 'admin') {
      res = await loginApi.logininfo();
    } else {
      res = await loginApi.userinfo();
    }

    // 处理返回的数据结构
    let userInfo = null;
    if (res.data) {
      // 数据在data字段中
      userInfo = res.data;
    } else {
      // 数据直接在根对象中
      userInfo = res;
    }

    // 设置用户信息
    loginAdmin.value = {
      ...loginAdmin.value,
      ...userInfo,
      name: userInfo.adminname || userInfo.username || "未登录"
    };
  } catch (error) {
    console.error("获取用户信息失败:", error);
    // Token无效或过期，清除并跳转到登录页
    localStorage.removeItem("token");
    router.push('/login');
  }
}

// 用户下拉菜单点击事件
function handleSelect(key, keyPath) {
  if (key === 'logout') {
    logout(); // 退出登录
  }
}

// 左侧菜单跳转事件
function handleMenu(key) {
  if (key) {
    router.push(key);
  }
}

// 退出登录逻辑
function logout() {
  // 清除Token
  localStorage.removeItem("token");
  // 跳转到登录页
  router.push('/login');
}
const isAdminLogin = () => {
  return loginUser.value.role === 'admin';
}
// 菜单：保留原有行程规划系统业务模块
const menuData = ref([
  {name: '用户管理', icon: 'User', children: [
      {name: '用户列表', icon: 'UserFilled', path: "/user"},
    ]},
  {name: '景点管理', icon: 'Location', children: [
      {name: '景点列表', icon: 'List', path: "/attraction"},
    ]},
  {name: '行程管理', icon: 'Calendar', children: [
      {name: '行程列表', icon: 'Document', path: "/itinerary"},
      // {name: '行程详情', icon: 'Tickets', path: "/itinerary_detail"},
    ]},
  {name: '收藏管理', icon: 'Star', children: [
      {name: '收藏列表', icon: 'StarFilled', path: "/favorites"},
    ]},
  {name: '评论管理', icon: 'ChatLineSquare', children: [
      {name: '评论列表', icon: 'ChatDotSquare', path: "/review"},
    ]},
  {name: '用户活动管理', icon: 'User', children: [  // 新增用户活动管理菜单
      {name: '活动记录列表', icon: 'Histogram', path: "/user_activity"},  // 对应User_activity表的列表页面
    ]},
  {name: '通知管理', icon: 'Bell', children: [
      {name: '通知列表', icon: 'BellFilled', path: "/notification"},

    ]},
  {
    name: '管理员管理', icon: 'User', children: [
      {name: '管理员列表', icon: 'UserFilled', path: '/admin'
      }
    ]
  },
  {
    name:'轮播图管理', icon:'Picture', children: [
      {name: '轮播图列表', icon: 'Collection', path: '/carousel'}
    ]
  }
  // {
  //   name:'AI客服',icon:'ChatDotRound',children: [
  //     {
  //       name:'智能客服',icon:'Service',path: '/ai-chat'
  //     }
  //   ]
  // }

]);

// 普通用户菜单
const userMenuData = ref([
  {name: '首页轮播', icon: 'Picture', children: [
      {name: '轮播展示', icon: 'Collection', path: "/carousel"},
    ]},
  {name: '个人中心', icon: 'User', children: [
      {name: '个人资料', icon: 'User', path: "/user"},
      // {name: '修改密码', icon: 'Lock', path: "/user/change-password"}
    ]},
  {name: '景点浏览', icon: 'Location', children: [
      {name: '景点列表', icon: 'List', path: "/attraction"},
    ]},

  {name: '我的行程', icon: 'Calendar', children: [
      {name: '行程列表', icon: 'Document', path: "/itinerary"},
      // {name: '创建行程', icon: 'Plus', path: "/itinerary/create"}
    ]},
  {name: '我的收藏', icon: 'Star', children: [
      {name: '收藏列表', icon: 'StarFilled', path: "/favorites"}
    ]},
  {name: '评论列表', icon: 'ChatLineSquare', children: [
      {name: '评论列表', icon: 'ChatDotSquare', path: "/review"}
    ]},
  {name: '通知中心', icon: 'Bell', children: [
      {name: '我的通知', icon: 'BellFilled', path: "/notification"}
    ]},
  // {name: '活动管理', icon: 'User', children: [
  //     {name: '活动记录列表', icon: 'Histogram', path: "/user_activity"},  // 对应User_activity表的列表页面
  //   ]},
  {name: 'AI客服', icon: 'ChatDotRound', children: [
      {name: '智能客服', icon: 'Service', path: "/ai-chat"},
    ]}
]);

// 根据用户角色选择菜单
const getMenuData = () => {
  return isAdminLogin() ? menuData.value : userMenuData.value;
};
// 左侧菜单展开折叠状态
const isCollapse = ref(false);
</script>


<template>
  <div class="trip-layout">
    <el-container>
      <!-- 1. 顶部导航：渐变起点（青绿色），衔接整体渐变 -->
      <el-header class="header-gradient">
        <el-menu
            :default-active="activeIndex"
            class="header-menu"
            mode="horizontal"
            :ellipsis="false"
            text-color="#2d6a66"
            active-text-color="#e66465"
            @select="handleSelect"
        >
          <el-menu-item index="0">
            <img style="height: 80%" src="@/assets/logo.png" alt="旅小帮" />
            <span style="padding-left: 50px; font-size: 24px; font-weight: 500;">旅小帮-智能旅游行程规划系统</span>
          </el-menu-item>
          <div class="flex-grow" />
          <!-- 管理员下拉菜单 -->
          <el-sub-menu index="1" class="admin-submenu">
            <template #title>
              <el-icon class="admin-icon"><Admin /></el-icon>
              {{loginAdmin.name}}
            </template>
            <!--            <el-menu-item index="1-1" class="submenu-item">修改信息</el-menu-item>-->
            <!--            <el-menu-item index="1-2" class="submenu-item">重置密码</el-menu-item>-->
            <el-menu-item index="logout" class="submenu-item logout-item">
              退出登录
              <el-icon class="logout-icon"><Logout /></el-icon>
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-header>

      <el-container>
        <!-- 2. 左侧边栏：渐变过渡（从青绿色到浅粉色） -->
        <el-aside :width="isCollapse ? '60px' : '220px'" class="aside-gradient">
          <!-- 折叠图标 -->
          <div style="height: 60px;line-height: 60px; text-align: right; color: #2d6a66; font-size: 20px; margin-right: 24px;">
            <el-icon @click="isCollapse = !isCollapse" class="collapse-icon">
              <Expand v-if="isCollapse" />
              <Fold v-else />
            </el-icon>
          </div>
          <!-- 侧边菜单 -->
          <el-menu
              active-text-color="#e66465"
              class="aside-menu"
              default-active="/attraction"
              text-color="#2d6a66"
              :collapse="isCollapse"
              @select="handleMenu"
          >
            <!-- 动态生成菜单 -->
            <el-sub-menu v-for="(menu, index) in getMenuData()" :key="index" :index="index.toString()">
              <template #title>
                <component
                    class="menu-icon"
                    :is="menu.icon"
                    style="width: 1em; height: 1em; margin-right: 8px"
                ></component>
                <span>{{ menu.name }}</span>
              </template>
              <el-menu-item
                  v-for="(child, ind) in menu.children"
                  :key="ind"
                  :index="child.path"
                  class="submenu-item"
              >
                <el-icon>
                  <component :is="child.icon" class="submenu-icon"></component>
                </el-icon>
                <span>{{ child.name }}</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>

        <!-- 3. 主内容区：渐变终点（浅粉色），与侧边栏衔接 -->
        <el-main class="main-gradient">
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<style scoped>
/* 基础全屏设置：确保页面无留白 */
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden;
}

.flex-grow {
  flex-grow: 1;
}

/* 整体布局容器：统一渐变基调 */
.trip-layout,
.el-container {
  height: 100vh;
  width: 100vw;
  margin: 0;
  padding: 0;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

/* 1. 顶部导航（header-gradient）：使用135度渐变，衔接整体风格 */
.header-gradient {
  --el-header-padding: 0;
  --el-header-height: 80px;
  box-sizing: border-box;
  flex-shrink: 0;
  height: var(--el-header-height);
  width: 100%;
  padding: var(--el-header-padding);
  /* 顶部导航使用统一渐变 */
  background: linear-gradient(135deg,  #a1c4fd 0%, #c2e9fb 100%);
  box-shadow: 0 2px 10px rgba(168, 237, 234, 0.4); /* 青绿色阴影增强层次感 */
  z-index: 10; /* 确保导航栏在内容上方 */
}
/* 顶部菜单样式：透明背景，继承顶部渐变 */
.header-menu {
  height: 100%;
  width: 100%;
  background: transparent !important; /* 清除默认背景，显示顶部渐变 */
  border-bottom: none;
}

/* 用户下拉菜单样式：与渐变协调 */
.user-submenu {
  margin-right: 20px;
}
.user-icon {
  margin-right: 6px;
  color: #e66465; /* 粉色图标，呼应渐变终点 */
}
.submenu-item {
  background: rgba(255, 255, 255, 0.8) !important; /* 半透明白色，不遮挡内容 */
  color: #2d6a66 !important; /* 青绿色文字，与渐变起点呼应 */
}
.submenu-item:hover {
  background: rgba(255, 245, 245, 0.9) !important; /* hover偏粉，贴合渐变趋势 */
}
.logout-item {
  color: #e66465 !important; /* 退出登录用粉色强调，明确交互 */
}
.logout-icon {
  margin-left: 6px;
}

/* 2. 左侧边栏（aside-gradient）：渐变过渡核心区域 */
.aside-gradient {
  height: calc(100vh - 80px); /* 减去顶部高度，填满剩余空间 */
  box-sizing: border-box;
  /* 侧边栏保持垂直渐变，与整体风格衔接 */
  background: linear-gradient(180deg, #a1c4fd 0%, #c2e9fb 100%);
  transition: width 0.3s ease;
  box-shadow: 2px 0 10px rgba(254, 214, 227, 0.3); /* 粉色阴影平衡视觉 */
}

/* 侧边菜单样式：透明背景，继承侧边栏渐变 */
.aside-menu {
  height: calc(100% - 60px); /* 减去折叠图标区域高度 */
  width: 100%;
  background: transparent !important; /* 清除默认背景，显示侧边栏渐变 */
  border-width: 0;
}

/* 侧边主菜单项：hover效果贴合渐变 */
.el-sub-menu__title {
  font-size: 16px;
  height: 50px;
  line-height: 50px;
  transition: background 0.3s ease;
}
.el-sub-menu__title:hover {
  background: rgba(255, 255, 255, 0.2) !important; /* 半透明hover，不破坏渐变 */
}

/* 侧边子菜单项：增强层次感 */
.submenu-item {
  font-size: 16px;
  height: 50px;
  line-height: 50px;
  background: rgba(255, 255, 255, 0.15) !important;
  margin: 0 8px !important;
  border-radius: 4px !important;
  margin-bottom: 4px !important;
}
.submenu-item:hover {
  background: rgba(255, 255, 255, 0.3) !important;
  color: #e66465 !important; /* hover文字变粉，贴合渐变终点 */
}
.submenu-icon {
  width: 1.2em;
  height: 1.2em;
}

/* 菜单图标样式：与文字颜色统一 */
.menu-icon {
  display: inline-block;
  color: #2d6a66;
}

/* 折叠图标：交互反馈优化 */
.collapse-icon {
  cursor: pointer;
  transition: transform 0.3s ease, color 0.3s ease;
  color: #2d6a66;
}
.collapse-icon:hover {
  transform: scale(1.1);
  color: #e66465; /* hover变粉，暗示渐变方向 */
}

/* 3. 主内容区（main-gradient）：使用统一135度渐变，强化整体风格 */
.main-gradient {
  height: calc(100vh - 80px); /* 减去顶部高度，填满剩余空间 */
  padding: 20px;
  box-sizing: border-box;
  /* 主内容区改为135度渐变，与顶部和整体布局保持一致 */
  background: linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%);
  overflow-y: auto; /* 内容过多时内部滚动，不影响整体布局 */
  /* 增加内阴影，区分内容区与侧边栏 */
  box-shadow: inset 0 0 15px rgba(255, 255, 255, 0.2);
}

/* 折叠状态适配：确保渐变连贯 */
.el-aside.collapse {
  width: 60px;
}

/* 菜单选中状态强化：用粉色突出当前项，贴合渐变终点 */
.el-menu-item.is-active,
.el-sub-menu.is-active > .el-sub-menu__title {
  color: #e66465 !important;
  font-weight: 500;
}
</style>
